#include "BaseView.h"

using namespace view;

BaseView::BaseView(Entity* entity, SDLSurface* parentSurface) : EntityView(entity, parentSurface)
{
	textSize = 12;
	initializeFont();
	initializeLifeMeter();
}

BaseView::~BaseView(void)
{
}

void BaseView::paint(void)
{
	if (entity)
	{
		lifeProperty.get()->notifyListener();
		EntityView::paint();
		drawLifeMeter();
		drawName();
	}
}

void BaseView::initializeLifeMeter(void)
{
	int maximumProgress = ((Base*)entity)->getLife();
	BaseLifeMonitor* lifeMonitor = new BaseLifeMonitor(0, maximumProgress, maximumProgress);
	lifeProperty.reset(new BaseLifeProperty((Base*)entity));
	lifeProperty->addPropertyChangeListener(lifeMonitor);
	lifeMeter.reset(new SDLProgressBar(lifeMonitor, parentSurface));
	lifeMeter->setWidth((int)(getWidth()-40.0+0.5));
	lifeMeter->setHeight(8);
	lifeMeter->setBorderColor(new Color(0, 255, 0, 255));
	lifeMeter->setBackgroundColor(new Color(0, 0, 0, 255));
	lifeMeter->setForegroundColor(new Color(0, 255, 0, 255));
}

void BaseView::drawLifeMeter(void)
{
	lifeMeter->setX((int)(getX()+20.0+0.5));
	lifeMeter->setY((int)(getY()+getHeight()/2-lifeMeter->getHeight()/2+0.5));
	lifeMeter->draw();
}

void BaseView::drawName(void)
{
	if (font)
	{
		Base* base = (Base*)entity;
		TTF_SetFontStyle(font, 0);
		SDL_Color color = {0, 255, 0};
		SDL_Surface* textSurface = TTF_RenderUTF8_Blended(font, base->getName().c_str(), color) ;
		if (textSurface != NULL)
		{
			SDL_Rect source;
			source.x = 0;
			source.y = 0;
			source.w = (Uint16)(getWidth()+0.5);
			source.h = (Uint16)(getHeight()+0.5);

			double nameHeight = textSize*2;
			SDL_Rect destination;
			destination.x = (Sint16)(base->getX()+20+0.5);
			destination.y = (Sint16)(base->getY()+getHeight()/2-lifeMeter->getHeight()/2-nameHeight+0.5);
			destination.w = (Uint16)(getWidth()+0.5);
			destination.h = (Uint16)(getHeight()+0.5);
			SDL_BlitSurface(textSurface, &source, parentSurface->getSurface(), &destination);
			SDL_FreeSurface(textSurface);
		}
	}
}

void BaseView::initializeFont(void)
{
	font = TTF_OpenFont("..\\fonts\\arial.ttf", textSize);
	if (!font)
	{
		string message("No es posible abrir el font arial.ttf. El error reportado por SDL es: '");
		message.append(TTF_GetError()).append("'.");
		Logger::instance().log(message);
	}
}
